//generate an ajax manger named clearQueue
var ajax_manager = $.manageAjax.create('clearQueue', {
    abortOld: true
});

function checkUsername(rewrite) {
    var username = $("#username").val();
    console.log("Checking username " + username);

    ajax_manager.abort();
    ajax_manager.add({
        success: function(payload) {
            if (payload.newName) {
                console.log("Suggesting username " + payload.newName);
                if (rewrite) {
                    $("#username").val(payload.newName);
                }
            }
        },
        url: check_username_link,
        data: { "username" : username },
    });
}


$(document).ready(function() {

    $("#first_name, #last_name").slugIt({
        output: '#username',
        space: '.',
        events: 'input',
        modify : function() {
            var first_name = $("#first_name").val();
            var last_name = $("#last_name").val();
            var dot = (last_name.length === 0 || first_name.length === 0) ? '' : '.';
            return first_name + dot +last_name;
        }
    });

    $("#username").bind("input", function(event) {
        checkUsername(false);
    });

    $("#first_name, #last_name").bind("input", function() {
        if ($("#first_name").val().length != 0 && $("#last_name").val().length != 0) {
            checkUsername(true);
        }
    })

})